/**
 * 文件处理工具
 *@author yg
 *@date 2020-11-10
 */
import "./mammoth/mammoth.browser";
import "./jszip/jszip.min";
import saveAs from "./jszip/FileSaver";

import {Message} from "element-ui"

import Store from '../store'

var arrayJson=new Array();
var Index = 0;
var AllNum = 0;
//=============================================docx======处理============mammoth.browser.js===========开始========================
//01-文件操作
export async function handleFile(arrayBuffer,allNum,allData,index,callback){
    AllNum = allNum;
    await mammoth.convertToHtml({arrayBuffer: arrayBuffer}).then((res)=>{
        handleResult(res,index,allData,function(data){
            callback(data);
        });
    }).done();
}
//02-文件内容转换
function readFileInputEventAsArrayBuffer(file, callback){
	var reader = new FileReader();
	reader.onload = function(loadEvent) {
	    var arrayBuffer = loadEvent.target.result;
	    callback(arrayBuffer);
	};
	reader.readAsArrayBuffer(file);
}
//03-结果处理
function handleResult(result,index,allData,callback) {
	$(result.value).find("img").each(function(index,ele){
		//图片描述
		var describe= $(ele).parent().prev().text();
		//图片内容
		var imgContent=$(ele).attr("src");
		var obj={"describe":describe,"img":imgContent}
		arrayJson.push(obj);
	});
    Index++;
    let newArray = JSON.parse(JSON.stringify(Store.getters.getFileDoc));
    newArray[index].status = 1;
    Store.dispatch('setFileDoc', newArray);
    if(Index>=AllNum){
        //图片组装
        var zip = new JSZip();
        for(let index in arrayJson){
            //单张下载
            //downloadFile(arrayJson[index].describe,arrayJson[index].img);

            //批量添加图片
            var img = zip.folder('images'); //添加一个文件夹
            let blob=base64ToBlob(arrayJson[index].img); //二进制数据
            img.file(arrayJson[index].describe+".jpg",blob,{base64: true}); //文件夹下添加图片
        }
        //下载图片
        zip.generateAsync({type:"blob"}).then(function(content){
            saveAs(content, "images.zip"); //FileSaver.js Api
        });

        Index = 0;
        Message({
            message:"解析图片成功",
            type: "success"
        });

        let newArrays = JSON.parse(JSON.stringify(allData));
        newArrays.forEach((items,index)=>{
            items.status = 1;
        });
        callback(newArrays);
    }
}

//下载单张图片
function downloadFile(fileName,content) { //下载base64图片
    var base64ToBlob = function(code) {
        let parts = code.split(';base64,');
        let contentType = parts[0].split(':')[1];
        let raw = window.atob(parts[1]);
        let rawLength = raw.length;
        let uInt8Array = new Uint8Array(rawLength);
        for(let i = 0; i < rawLength; ++i) {
            uInt8Array[i] = raw.charCodeAt(i);
        }
        return new Blob([uInt8Array], {
            type: contentType
        });
    };
    let aLink = document.createElement('a');
    let blob = base64ToBlob(content); //new Blob([content]);
    let evt = document.createEvent("HTMLEvents");
    evt.initEvent("click", true, true); //initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
    aLink.download = fileName;
    aLink.href = URL.createObjectURL(blob);
    aLink.click();
};

//图片批量压缩下载
//=============================================docx======处理============mammoth.browser.js===========结束========================


//=================================常用方法================开始==================================
 var base64ToBlob = function(code) {
        let parts = code.split(';base64,');
        let contentType = parts[0].split(':')[1];
        let raw = window.atob(parts[1]);
        let rawLength = raw.length;
        let uInt8Array = new Uint8Array(rawLength);
        for(let i = 0; i < rawLength; ++i) {
            uInt8Array[i] = raw.charCodeAt(i);
        }
        return new Blob([uInt8Array], {
            type: contentType
        });
    };
//=================================常用方法================结束==================================
